module.exports = function ($scope, $state, $modal, toaster, getDate, Excel, $timeout, date2str, mechanism, $resource) {
    $scope.count_type_arr = [
        {
            'label': '历史统计',
            'value': '0',
        },
        {
            'label': '当日统计',
            'value': '1',
        },
    ];


    $scope.objs = [];
    $scope.ExcelName = '';

    $scope.searchform = {};
    $scope.searchform.company_type = '1';
    $scope.searchform.count_type = '0';
    $scope.searchform.ticket_type = '1';
    $scope.tempData = {};
    $scope.tempSearchData = {};
    $scope.selectedCompany = '';

    //有效区间
    $scope.section = {};
    $scope.section.start = {
        'date': {
        }
    };
    $scope.section.start.date = {
        'label': date2str(new Date(new Date().getTime() - 1 * 24 * 3600 * 1000)),
        'value': date2str(new Date(new Date().getTime() - 1 * 24 * 3600 * 1000)),
        'opened': false
    };
    $scope.section.end = {
        'date': {
        }
    };
    $scope.section.end.date = {
        'label': date2str(new Date(new Date().getTime() - 1 * 24 * 3600 * 1000)),
        'value': date2str(new Date(new Date().getTime() - 1 * 24 * 3600 * 1000)),
        'opened': false
    };

    // $scope.inlineOptions = {
	// 	maxDate : date2str(new Date())
	// };

    $scope.open = function ($event, item) {
        $event.preventDefault();
        $event.stopPropagation();
        item.opened = true;
    }

    $scope.clearDate = function (obj) {
        delete obj.date;
    };

    //机构树
    $scope.isOnlyOneCompany = false;
    function mechanismtree() {
        mechanism.save({ 'suboffice': '1' }, function (res) {
            if (res.data.length == 1) {
                $scope.tempSearchData = {
                    id: res.data[0].id,
                    name: res.data[0].name,
                    code: res.data[0].code
                };
                $scope.selectedCompany = res.data[0].name;
                $scope.isOnlyOneCompany = true;
                $scope.companyarr = [
                    {
                        'label': '本级',
                        'value': '1',
                    }
                ];
                $scope.searchform.company_type = '1';
            } else {
                $scope.tempData = angular.copy(res.data);
                $scope.data = transData(res.data, 'id', 'parent_id', 'nodes');
                $scope.tempSearchData = {
                    id: $scope.data[0].id,
                    name: $scope.data[0].name,
                    code: $scope.data[0].code
                };
                $scope.selectedCompany = $scope.data[0].name;
                $scope.companyarr = [
                    {
                        'label': '本级',
                        'value': '1',
                    },
                    {
                        'label': '下级',
                        'value': '2',
                    },
                    {
                        'label': '本级+下级',
                        'value': '3',
                    }
                ]
            }
            $scope.orderSearch();
        });
    }
    mechanismtree();

    function transData(a, idStr, pidStr, chindrenStr) {
        var r = [],
            hash = {},
            id = idStr,
            pid = pidStr,
            children = chindrenStr,
            i = 0,
            j = 0,
            len = a.length;
        for (; i < len; i++) {
            hash[a[i][id]] = a[i];
        }

        for (; j < len; j++) {
            var aVal = a[j],
                hashVP = hash[aVal[pid]];
            if (hashVP) {
                !hashVP[children] && (hashVP[children] = []);
                hashVP[children].push(aVal);
            } else {
                r.push(aVal);
            }
        }
        return r;
    }

    $scope.openCompanyTree = function () {
        var modalInstance = $modal.open({
            template: require('../views/tree.html'),
            controller: 'tree',
            size: 'md',
            resolve: {
                data: function () {
                    return $scope.data;
                },
                toaster: function () {
                    return toaster
                }
            }
        });
        //关闭模态框刷新页面
        modalInstance.result.then(function (result) {
            $scope.getit(result);
            $scope.orderSearch();
        });
    }

    $scope.myKeyup = function (e) {
        //IE 编码包含在window.event.keyCode中，Firefox或Safari 包含在event.which中
        var keycode = window.event ? e.keyCode : e.which;
        if (keycode == 13) {
            $scope.load();
        }
    };

    $scope.payment_type_list = "1,2,4,5,7";
    $scope.count_buy = 0;
    $scope.count_used = 0;
    $scope.count_back = 0;
    $scope.count_total_buy = 0;
    $scope.count_total_back = 0;
    $scope.count_total_money = 0;
    $scope.load = function () {

        if ($scope.section.start.date.label == null) {
            toaster.warning({ title: '', body: '请选择开始日期' });
            return false;
        } else if (typeof $scope.section.start.date.label === 'string') {
            var start = $scope.section.start.date.label;
        } else {
            var start = date2str($scope.section.start.date.label);
        }
        if ($scope.section.end.date.label == null) {
            toaster.warning({ title: '', body: '请选择结束日期' });
            return false;
        } else if (typeof $scope.section.end.date.label === 'string') {
            var end = $scope.section.end.date.label;
        } else {
            var end = date2str($scope.section.end.date.label);
        }
        // if (!($scope.section.start.date && $scope.section.end.date)) {
        // 	alert('请选择统计时间');
        // 	return false;
        // }
        if (!$scope.selectedCompany) {
            alert('请选择机构');
            return false;
        }
        $scope.ExcelName = start + '至' + end;
        if($scope.payment_type_list.substring($scope.payment_type_list.length -1, $scope.payment_type_list.length) == ","){
            $scope.payment_type_list = $scope.payment_type_list.substring(0, $scope.payment_type_list.length -1)
        }
        var para = {
            start_date: start,
            end_date: end,
            payment_type_list: $scope.payment_type_list
        };

        para = angular.extend($scope.searchform, para);
        $resource("/api/ac/tc/ticketCountService/countByCompnycodePaymentType", {}, {}).save(para, function (res) {
            if (res.errcode != 0) {
                toaster.error({ body: res.errmsg })
            }
            $scope.ticket_type_flag = $scope.searchform.ticket_type;
            if (res.data[0]) {
                $scope.objs = res.data;
            } else {
                $scope.objs = [];
            }
            for (var index = 0; index < $scope.objs.length; index++) {
                $scope.objs[index].count_buy = 0;
                $scope.objs[index].count_used = 0;
                $scope.objs[index].count_back = 0;
                $scope.objs[index].count_total_buy = 0;
                $scope.objs[index].count_total_back = 0;
                $scope.objs[index].count_total_money = 0;
                for (var i = 0; i < $scope.objs[index].list.length; i++) {
                    $scope.objs[index].count_buy += parseFloat($scope.objs[index].list[i].buy);
                    $scope.objs[index].count_used += parseFloat($scope.objs[index].list[i].used);
                    $scope.objs[index].count_back += parseFloat($scope.objs[index].list[i].back);
                    $scope.objs[index].count_total_buy += parseFloat($scope.objs[index].list[i].total_buy);
                    $scope.objs[index].count_total_back += parseFloat($scope.objs[index].list[i].total_back);
                    $scope.objs[index].count_total_money += parseFloat($scope.objs[index].list[i].total_money);
                }
                $scope.objs[index].count_buy = $scope.objs[index].count_buy.toFixed(2);
                $scope.objs[index].count_used = $scope.objs[index].count_used.toFixed(2);
                $scope.objs[index].count_back = $scope.objs[index].count_back.toFixed(2);
                $scope.objs[index].count_total_buy = $scope.objs[index].count_total_buy.toFixed(2);
                $scope.objs[index].count_total_back = $scope.objs[index].count_total_back.toFixed(2);
                $scope.objs[index].count_total_money = $scope.objs[index].count_total_money.toFixed(2);
            }
        });
    };
    // $scope.load();

    $scope.getit = function (obj) {
        $scope.tempSearchData = {
            id: obj.$modelValue.id,
            name: obj.$modelValue.name,
            code: obj.$modelValue.code
        };
        $scope.selectedCompany = obj.$modelValue.name;
    };

    $scope.orderSearch = function () {
        $scope.searchform.code = $scope.tempSearchData.code;
        $scope.searchform.list = [];

        for (var index = 0; index < $scope.tempData.length; index++) {
            var element = $scope.tempData[index];
            if (element.parent_id == $scope.tempSearchData.id) {
                $scope.searchform.list.push({ code: element.code, list: [], id: element.id });
            }
        }

        for (var index = 0; index < $scope.searchform.list.length; index++) {
            var element = $scope.searchform.list[index];
            for (var index_temDat = 0; index_temDat < $scope.tempData.length; index_temDat++) {
                var tempArray = [];
                tempArray = $scope.tempData[index_temDat].parent_ids.split(',');
                for (var index_temArr = 0; index_temArr < tempArray.length; index_temArr++) {
                    if (tempArray[index_temArr] == element.id) {
                        $scope.searchform.list[index].list.push($scope.tempData[index_temDat].code);
                        break;
                    }
                }
            }
        }

        $scope.load();
    }

    $scope.infringementNotices = [
        {
            IsPay: '扣款',
            Operate: '通知'
        }
    ];

    $scope.exportToExcel = function (tableId) {
        $timeout(function () {
            document.getElementById("dlink").href = Excel.tableToExcel(tableId, 'sheet1');
            //document.getElementById("dlink").download = "1122b.xls";//这里是关键所在,当点击之后,设置a标签的属性,这样就可以更改标签的标题了
            document.getElementById("dlink").click();
        }, 100); // trigger download


        // $scope.exportHref = Excel.tableToExcel(tableId, '哈哈哈哈哈sheet1');
        // $timeout(function () { location.href = $scope.exportHref; }, 100); // trigger download
    }
    $scope.payTypeList = [
        // {
        //     name: "默认",
        //     model: "0",
        //     isCheck: true
        // },
        {
            name: "支付宝",
            model: "1",
            isCheck: true
        },
        {
            name: "微信",
            model: "2",
            isCheck: true
        },
        // {
        //     name: "网银在线",
        //     model: "3",
        //     isCheck: true
        // },
        {
            name: "账户",
            model: "4",
            isCheck: true
        },
        {
            name: "现金",
            model: "5",
            isCheck: true
        },
        {
            name: "批量",
            model: "7",
            isCheck: true
        },
        // {
        //     name: "同业",
        //     model: "8",
        //     isCheck: true
        // },
        // {
        //     name: "半价",
        //     model: "9",
        //     isCheck: true
        // }
    ]

    $scope.allChange = function() {
        if ($scope.pay_type_all) {
            $scope.payment_type_list = "";
            for (var index = 0; index < $scope.payTypeList.length; index++) {
                var element = $scope.payTypeList[index];
                element.isCheck = true;
                $scope.payment_type_list += element.model + ',';
            }
        }else{
            $scope.payment_type_list = "";
            for (var index = 0; index < $scope.payTypeList.length; index++) {
                var element = $scope.payTypeList[index];
                element.isCheck = false;
            }
        }
    }

    $scope.$watch('payTypeList', function (newValue) {
        var isTrue = true;
        $scope.payment_type_list = "";
        for (var index = 0; index < $scope.payTypeList.length; index++) {
            var element = $scope.payTypeList[index];
            if(!element.isCheck){
                isTrue = false;
                continue;
            }else {
                $scope.payment_type_list += element.model + ',';
            }
        }
        if (isTrue) {
            $scope.pay_type_all = true;
        }else{
            $scope.pay_type_all = false;
        }
	}, true);

    $scope.$watch('searchform.count_type', function (newValue) {
        if($scope.searchform.count_type == '1'){
            $scope.section.start.date = {
                'label': date2str(new Date()),
                'value': date2str(new Date()),
                'opened': false
            };
            $scope.section.end.date = {
                'label': date2str(new Date()),
                'value': date2str(new Date()),
                'opened': false
            };
            // $scope.inlineOptions = {
            //     maxDate: new Date()
            // };
        } else {
            // $scope.inlineOptions = {
            //     maxDate: new Date().setDate(new Date().getDate - 1)
            // };
        }
	}, true);

    $scope.$watch('section', function (newValue) {
        if($scope.searchform.count_type == '1'){
            var start = "";
            var end = "";
            if (typeof $scope.section.start.date.label === 'string') {
                start = $scope.section.start.date.label;
            } else {
                start = date2str($scope.section.start.date.label);
            }
            if (typeof $scope.section.end.date.label === 'string') {
                end = $scope.section.end.date.label;
            } else {
                end = date2str($scope.section.end.date.label);
            }
            if (start != date2str(new Date()) || end != date2str(new Date()) ) {
                $scope.searchform.count_type = '0'
            }
        }
	}, true);


};